  /*
  * MinIO Cloud Storage (C) 2018 MinIO, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */

  import React from "react";
  import { createStyles, makeStyles, withStyles, Theme } from '@material-ui/core/styles';
  import ReactEcharts from 'echarts-for-react';
  import Alert from '@material-ui/lab/Alert';
  import IconButton from '@material-ui/core/IconButton';
  import Collapse from '@material-ui/core/Collapse';
  import CloseIcon from '@material-ui/icons/Close';
  import api from "../../../common/api";
  import { ChartUrl, beforeNowtimeByMinu, timeConvert } from "./types";

const styles = (theme: Theme) =>
  createStyles({
    alert: {
      position: "absolute",
      width: "100%",
      textAlign: "center",
      zIndex: 1000, 
      top: 35
    },
    alertPop: {
      margin: "0 auto",
      width: "130px"
    },
    chart: {
      height: '350px', 
      width: '100%', 
      marginTop: -20,
      marginBottom: -40
    },
});

interface ChartState {
  classes: any;
  // option: object,
  // open: false,
}
export class D_NodeCPU extends React.Component<ChartState, any> {
  constructor(props:any){
    super(props);
    this.state = {
      loading: false,
      msg:"",
      xrate:[],
      xdata:[],
      dataWarn:"",
      open: false
    };
  };
  setOpen(a:boolean){
    this.setState({
      open: a
    })
  }
  getChart() {
    // CPU 每分钟使用率
    let url = ChartUrl+"(1-((sum(increase(node_cpu_seconds_total{mode='idle'}[1m]))by(instance))/(sum(increase(node_cpu_seconds_total[1m]))by(instance))))*100&start="+Date.parse(beforeNowtimeByMinu(60)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step=14";
    api
      .invoke("GET", url)
      .then((res) => {
        var rootData = res.data.result;
        var xrate = new Array();
        var xdata = new Array();
        if(rootData != []){
          for(var i=0;i<rootData.length;i++){
            console.log(rootData[i])
            var x = rootData[i].values.length-1
            xrate[i] = rootData[i].metric.instance
            xdata[i] = parseFloat(rootData[i].values[x][1]).toFixed(1)
            // console.log(xrate[i] + xdata[i])
            // xrate.push(rootData[i].metric.instance)
            // xdata.push(parseFloat(rootData[i].values[x][1]).toFixed(2))
          }
          // console.log(xrate)
          // console.log(xdata)
          this.setState({
            xrate: xrate,
            xdata: xdata
          })
        }else{
          this.setState({
            dataWarn: "暂无数据",
            loading: false 
          })
          this.setOpen(true);
        }
      })
      // .catch(err => {
      //   this.setState({
      //     dataWarn: "暂无数据2",
      //     loading: false 
      //   })
      //   this.setOpen(true);
      // });
  }
  componentDidMount(): void {
    var that = this
    that.getChart();
    var timer = setInterval(() => {
      let url = window.location.href
      if(url.indexOf("/dashboard") != -1){
        that.getChart();
      }else{
        clearInterval(timer)
      }
    }, 30000)
    // that.setState({
    //   xrate: ["192.168.1.200:9000","192.168.1.200:9000","192.168.1.200:9000","192.168.1.200:9100","192.168.1.200:9200","192.168.1.200:9090","192.168.1.200:9200","192.168.200.200:9090"],
    //   xdata: [34.00,88.00,78.00,74.00,88.00,18.00,34.00,10.6]
    // })
  }
  // componentDidUpdate(prevProps:any): void {
  //   if(prevProps.inputNode !== this.state.oldNode){
  //       this.getChart();
  //       var timer = setInterval(() => {
  //         let url = window.location.href
  //         if(url.indexOf("/dashboard") != -1){
  //           this.getChart(this.state.oldNode);
  //         }else{
  //           clearInterval(timer)
  //         }
  //       }, 25000)
  //   }
  // }
  // static getDerivedStateFromProps(nextProps:any, prevState:any) {
  //   // 当传入的type发生变化的时候，更新state
  //   if (nextProps.inputNode !== prevState.oldNode) {
  //     return {
  //       oldNode: nextProps.inputNode
  //     }
  //   }
  //   // 否则，对于state不进行任何操作
  //   return null;
  // }
  getOption= () => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
        left: 8
    },
    xAxis: {
      name: '%',
      type: 'value',
      axisLine: {//x轴线的颜色以及宽度
        show: true,
        lineStyle: {
          color: "#777",
          width: 1,
          type: "solid"
        }
      },
      axisTick: {
        show: false,
      },
      axisLabel: {//x轴文字的配置
        show: true,
        textStyle: {
          color: "#777",
        }
      },
      splitLine: {//分割线配置
        show:false,
        lineStyle: {
          color: "#777",
        }
      }
    },
    yAxis: {
      type: 'category',
      axisTick: {
        show: false,
      },
      data: this.state.xrate
    },
    series: [
      {
        type: 'bar',
        color: "#5793f3",
        label:{
          show: true,
          textBorderColor: '#2e7eff',
          textBorderWidth: 2,
          position: "insideLeft",
          offset:[180, 8],
          align: 'right',
          verticalAlign: 'bottom',
          formatter: '{b} {c}%',
          fontSize: 12,
        },
        data: this.state.xdata
      }
    ]
    
    // xAxis: {
    //   type: 'category',
    //   data: this.state.xrate
    // },
    // yAxis: {
    //     type: 'value'
    // },
    // series: [{
    //     data: this.state.xdata,
    //     type: 'bar',
    //     itemStyle:{
    //       normal: {
    //         color: function(params: any) {
    //           var colorList = [            
    //             '#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
    //             '#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',           
    //             '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'                     
    //           ];
    //           return colorList[params.dataIndex]           
    //         },
    //     }},
    //     showBackground: true,
    //     backgroundStyle: {
    //         color: 'rgba(220, 220, 220, 0.4)'
    //     }
    // }]
});
  render() {
    const { classes } = this.props;
    return (
      <div style={{position: "relative"}}>
        {this.state.open ? (
        <div className={classes.alert}>
          <Collapse in={this.state.open} className={classes.alertPop}>
            <Alert severity="error" style={{padding: "0 16px"}}>
              {this.state.dataWarn}
            </Alert>
          </Collapse>
        </div>
        ):(
          <ReactEcharts
          ref="chart"
          option={this.getOption()}
          className={classes.chart}/>
          )}
      </div>
    );
  }
};
export default withStyles(styles)(D_NodeCPU)